/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.components.defaults.taskFields

import cn.nkpro.elcube.annotation.NkNote
import cn.nkpro.elcube.platform.model.NkSelectItem
import cn.nkpro.elcube.security.UserAuthorizationService
import cn.nkpro.elcube.task.from.NkAbstractFormFieldType
import cn.nkpro.elcube.task.model.BpmFormField
import com.alibaba.fastjson.JSON
import groovy.util.logging.Slf4j
import org.camunda.bpm.engine.ProcessEngine
import org.camunda.bpm.engine.task.Task
import org.camunda.bpm.engine.variable.value.TypedValue
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Lazy
import org.springframework.stereotype.Component

import java.util.stream.Collectors
@NkNote("用户选择器")
@Component("NkTaskFieldUserSelector")
class NkTaskFieldUserSelector extends NkAbstractFormFieldType {

    @Autowired
    private UserAuthorizationService authorizationService
    @Autowired@Lazy
    protected ProcessEngine processEngine;

    @Override
    TypedValue convertToFormValue(TypedValue typedValue) {
        return typedValue
    }

    @Override
    TypedValue convertToModelValue(TypedValue typedValue) {
        return typedValue
    }

    @Override
    Object convertFormValueToModelValue(Object o) {
        return o
    }

    @Override
    String convertModelValueToFormValue(Object o) {
        return o!=null?o.toString():null
    }

    @Override
    void doPreprocess(BpmFormField field, Task task) {

        String groupKey = field.properties.get('groupKey')
        System.out.println("查出数据="+JSON.toJSONString(authorizationService.getGroupDetailByKey(groupKey)))
        if(groupKey){
            field.options = (
                authorizationService.getGroupDetailByKey(groupKey)
                    .getAccounts()
                    .stream()
                    .map({ account ->
                        new NkSelectItem(account.realname,account.id)
                    })
                    .collect(Collectors.toList())
            )
        }
        System.out.println("选项="+JSON.toJSONString(field.options))
    }
}
